package IFile;

use FileHandle;
use Moose;
use Data::Dumper;
use Data::UUID;

use Log;
use ILine;
use MooseX::Iterator;

has 'filename' => (
    is => 'rw',
    isa => 'Str',
);

has 'idata' => (
    is => 'rw',
    isa => 'ArrayRef[ILine]|Undef', 
    init_arg => undef,    
    );

has iter => (
        metaclass    => 'Iterable',
        iterate_over => 'idata',
    );

sub BUILD {
    my $s = shift;
#    my $log = Log->instance;
    
    if(! -f $s->filename) {
	$s->log->xsupererror("5f1e18f7-d5fc-3bb3-a111-0ae46db6877d",
			     $s->log->format("MODEL","",$s->filename." is not a plain file"));
    }
    $s->_read();
}


sub _read {
    my $self = shift;
    my $fh = FileHandle->new($self->filename,"r");
    $self->log->xsupererror("b0929d96-8b3a-3f5e-a464-c880d730b151",
			    $self->log->format("MODEL","","cannot open ".$self->filename))
	unless ($fh->open($self->filename));
    my $line = 0;
    my $idata = $self->idata;
    my $what;
    my $current_indent = 0;
    my $indent = 0;
    my $ug = new Data::UUID;
    my $raw_line;
    while(<$fh>) {
	# print STDERR $_;
	$raw_line = $_;
	chomp;
	$line++;
	if(/^\#/o) {
	    $indent=0;
	    $what = 'comment';
	}elsif(/^[\s\t]*$/o) {
	    $indent=0;
	    $what = 'empty';
	}else{
	    my $s1=length($_);
	    s/^\t+//o;
	    $indent=$s1-length($_);
	    $self->log->xsupererror("7dd0661c-23fd-3e58-868e-3fb755c9f1f6",
				   $self->log->format($self->filename,$line,"indent error (too much indent level)"))
		if($indent > $current_indent+1);
	    s/\s+$//go;
	    $what = 'data';
	    
	}	
	my $rec = ILine->new (
	    line => $line,
	    raw_value => $raw_value,
	    value => $_,
	    indent => $indent,
	    what   => $what,
	    guid   => $ug->create(),
	    origin => $self->filename,
	);
	$current_indent = $indent;
	push(@$idata,$rec);
    }
    $self->idata($idata);
    $fh->close; 
}



sub write {
	my $self = shift;
	my $fh = FileHandle->new($self->filename,"w");
	$self->log->xsupererror("b0929d96-8b3a-3f5e-a464-c880d730b151",
				$self->log->format("MODEL","","cannot open(write mode) ".$self->filename))
	    unless ($fh->open($self->filename));
	foreach my $i (@{$self->idata}) {
	    print $fh,$i->value."\n";
	}

}

sub delete {
	my $self = shift;
	my $n = shift;
	Utils::defence_between(__FILE__,__LINE__,'n',$n,0,scalar(@{$self->idata}));
	splice(@{$self->idata},$n,1);
}

sub insert {
    my $self = shift;
    my $n = shift;
    Utils::defence_between(__FILE__,__LINE__,'n',$n,0,scalar(@{$self->idata}));
    my $rec = shift;
    splice(@{$self->idata},$n,0,$rec);
}

sub subst {
    my $self = shift;
    my $n = shift;
    Utils::defence_between(__FILE__,__LINE__,'n',$n,0,scalar(@{$self->idata}));
    my $rec = shift;
    splice(@{$self->idata},$n,1,$rec);
}

sub push {
    my $self = shift;
    my $rec = shift;
    push(@{$self->idata},$rec);
}


no Moose;
__PACKAGE__->meta->make_immutable;
